# -*- coding: utf-8 -*-

from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
from odoo.exceptions import UserError


class Book(models.Model):
    _name = 'ebook.book'
    _description = "图书馆书籍管理"

    name = fields.Char(string="名字", required=True)
    image = fields.Binary(
        '图片'
    )
    description = fields.Text(string="书籍描述")
    author = fields.Text(string="作者")
    start_date = fields.Date(string="出版日期")
    oneprice = fields.Float(string="单价")
    allprice = fields.Float(string="总价", readonly=True, compute="count_total",
                            )
    address = fields.Html(string="收货地址")
    number = fields.Float(string="个数")
    publisher_id = fields.Many2one(
        'ebook.press', string='签约出版商', ondelete='no action', required=True, help='')

    state = fields.Selection(
        [
            ('edit', '编辑'),
            ('check', '审批中'),
            ('pass', '通过'),
            ('fail', '失败'),
        ],
        string='状态', default='edit', readonly=True, copy=False, track_visibility='onchange'
    )
    is_bad = fields.Boolean(
        '是否为问题图书',
        default=True
    )
    is_chat = fields.Boolean(
        '是否入账',
        default=False
    )
    sale_id = fields.Many2one(
        'ebook.user'
    )
    # has_book_id=fields.Many2one(
    #     'ebook.operator'
    # )



    def button_submit(self):
        return self.write({"state": "check"})

    def button_pass(self):
        return self.write({"state": "pass"})

    def button_fail(self):
        return self.write({"state": "fail"})

    @api.one
    @api.depends('number', 'oneprice')  # 总价为单价乘数量组成
    def count_total(self):
        self.allprice = self.number * self.oneprice

    def check_booked(self):
        self.ensure_one()
        if self.is_chat:
            raise UserError(_('已入账!') % self.name)
        else:
            try:
                return {
                    'type': 'ir.actions.act_window',
                    'view_type': 'form',
                    'view_mode': 'calendar,tree,form',
                    'res_model': 'ebook.sell',
                    'target': 'new',
                    'context': {
                        'default_ebook_sell_name': self.name,
                        'default_number': self.number
                    }
                }

            except Exception as e:
                raise UserError(_('错误：%s') % e)
